﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.ComponentModel;
using System.Windows.Threading;
using CCF20Model;

namespace ZICMonitor
{
    /// <summary>
    /// Interaction logic for Login.xaml
    /// </summary>
    public partial class FaultCounter : Window
    {
        private CCFCount ccfCount = null;
        private ZICMonitorModel zmm;
        private ZICModel zicModel;
        private BackgroundWorker bkWorker;
        private int QueryCount = 1;
        private bool isInitialzied = false;
        private bool isConnected = true;
        ProgressDialog myProgress;
        public FaultCounter()
        {
            InitializeComponent();
            zmm = new ZICMonitorModel();
            bkWorker = ((BackgroundWorker)this.FindResource("backgroundWorker"));
            bkWorker.WorkerSupportsCancellation = true;

        }

        private void Window_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            if (e.ClickCount == 2)
            {
                //double click, close the app
                App.Current.MainWindow.Close();

            }
            else
            {
                this.DragMove();
            }
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            double screenWidth = SystemParameters.WorkArea.Width;
            //double screenHeight = SystemParameters.WorkArea.Height;
            this.Left = screenWidth - this.Width - 30;
            this.Top = 0;
            
            DispatcherTimer zicTimer = new DispatcherTimer();
            zicTimer.Tick += new EventHandler(dispatcherTimer_Tick);
            zicTimer.Interval = new TimeSpan(0, 0, 3);
            zicTimer.Start();
            LoggerHelper.LogZICMonitor("计时器正常启动");

        }

        private void dispatcherTimer_Tick(object sender, EventArgs e)
        {
            ccfCount = zmm.GetCount();
            ccfCount.ZicAvailable = isConnected ? 1 : 0;
            this.txtZICAvailable.Foreground = isConnected ? new SolidColorBrush(Colors.White) : new SolidColorBrush(Colors.Red);
            this.DataContext = ccfCount;
            
            if (!bkWorker.IsBusy)
            {
                bkWorker.RunWorkerAsync("ZICSync");
            }
        }


        private void BackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {


                try
                {
                    ModelFactory modelFactory = new ModelFactory();
                    zicModel = new ZICModel(modelFactory);
                }
                catch (Exception ex)
                {
                    if (ex.Message.Contains("The underlying provider failed on Open"))
                    {
                        MessageBox.Show("ZICMonitor无法与数据库进行通讯，请检查配置文件");
                        Application.Current.Shutdown();
                    }
                    else
                    {
                        MessageBox.Show(ex.Message);
                        LoggerHelper.LogZICMonitor(ex.Message);
                        LoggerHelper.LogZICMonitor(ex.StackTrace);
                    }

                }

                SMSModel.ScheduleUrgentSMS();
                string timeType = (string)e.Argument;
                if (timeType == "ZICSync")
                {
                    if (QueryCount % 6 == 0)
                    {
                        //we connect to zic in a (5 times ) slower  frequency 
                        zicModel.GetDeviceRecord();
                        zicModel.GetCrash();
                        zicModel.GetDeviceStatus();
                        zicModel.GetDefectedProduct();
                        zicModel.SendManagerReportSMS();
                        zicModel.SendMonthlyReportSMS();
                        QueryCount = 1;
                        zicModel.UpdateZICInfo(true);
                        //CCF20Entities ccf20 = new CCF20Entities();
                        //SMSTest test1 = new SMSTest(ccf20);
                        //test1.SendMaintenanceMsg();
                    }
                    QueryCount++;
                }
                else if (timeType == "UploadStats")
                {
                    App.Current.Dispatcher.Invoke(
                                                    new Action(
                                                        () =>
                                                        {
                                                            myProgress = new ProgressDialog();
                                                            myProgress.Show();
                                                        }));
                    zicModel.UploadDayStats();
                    myProgress.UpdateProgress(0.25);
                    myProgress.UpdateStatus("完成当日注册信息的上传");
                    if (myProgress.Canceled)
                    {
                        return;
                    }
                    
                    zicModel.UploadDailyCareStats();
                    myProgress.UpdateProgress(0.50);
                    myProgress.UpdateStatus("完成客户关怀满意度信息的上传");
                    if (myProgress.Canceled)
                    {
                        return;
                    }

                    zicModel.UploadDailyFaultStatsByVehicleTypeStats();
                    myProgress.UpdateProgress(0.75);
                    myProgress.UpdateStatus("完成当日故障码统计上传");
                    if (myProgress.Canceled)
                    {
                        return;
                    }

                    zicModel.UploadDailyDeclineStatsByVehicleType();
                    myProgress.UpdateProgress(1.0);
                    myProgress.UpdateStatus("完成当日拒绝车辆统计上传");
                    App.Current.Dispatcher.Invoke(
                        new Action(
                            () =>
                            {
                                myProgress.Close();
                            }));
                }
                isConnected = true;

            }
            catch (Exception ex)
            {
                LoggerHelper.LogZICMonitorException(ex);
                zicModel.UpdateZICInfo(false);
                isConnected = false;
                LoggerHelper.LogZICMonitor("与ZIC链接中断");
            }
        }

        private void BackgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            //MessageBox.Show("done");
        }

        private void MenuItem_Click(object sender, RoutedEventArgs e)
        {
            MenuItem clickMenu = e.OriginalSource as MenuItem;
            if (clickMenu != null)
            {
                string header = clickMenu.Header.ToString();
                if (header == "上传统计信息")
                {

                    if (bkWorker.IsBusy)
                    {
                        bkWorker.CancelAsync();
                        MessageBox.Show("ZIC 接收程序正忙，请稍后在试");
                    }
                    else
                    {
                        bkWorker.RunWorkerAsync("UploadStats");
                    }
                }
                else if (header == "获取ZIC信息")
                {
                    isConnected = true;
                    LoggerHelper.LogZICMonitor("与ZIC重新连接");
                }
            }
        }



    }

}
